﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace MCPro
{
    /// <summary>
    /// Triple DES Cryptography Class
    /// </summary>
    public class DesDesDes
    {
        private static string key = "TheQuickBrownFoxJumpOverTheLazyDog";

        private static byte[] Encryption(string PlainText)
        {
            TripleDES des = CreateDES(key);
            ICryptoTransform ct = des.CreateEncryptor();
            byte[] input = Encoding.Unicode.GetBytes(PlainText);
            return ct.TransformFinalBlock(input, 0, input.Length);
        }

        private static string Decryption(string CypherText)
        {
            byte[] b = Convert.FromBase64String(CypherText);
            TripleDES des = CreateDES(key);
            ICryptoTransform ct = des.CreateDecryptor();
            byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
            return Encoding.Unicode.GetString(output);
        }

        private static TripleDES CreateDES(string key)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            TripleDES des = new TripleDESCryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
            des.IV = new byte[des.BlockSize / 8];
            return des;
        }

        /// <summary>
        /// Encrypt using the Three DES Technology
        /// </summary>
        /// <param name="value">string to be encrypt</param>
        public string Encrypt(string value)
        {
            byte[] buffer = Encryption(value);
            string EncryptedVal = Convert.ToBase64String(buffer);

            return EncryptedVal;
        }

        /// <summary>
        /// Decrypt the encrypted string
        /// </summary>
        /// <param name="value">string to be decrypt</param>
        public string Decrypt(string value)
        {
            string cleanString = value.Replace(' ', '+');
            string DecryptedVal = Decryption(cleanString);

            return DecryptedVal;
        }
    }
}